package com.example.securitydemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.example.securitydemo.model.pojo.TokenUser;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

public class JwtUtils {

    public static String generateUserToken(TokenUser user){
        List<String> authorities = user.getAuthorities();
        String[] authorityArray = null;
        if(CollectionUtils.isEmpty(authorities)){
            authorityArray = new String[]{};
        } else {
            authorityArray = new String[authorities.size()];
            authorities.toArray(authorityArray);
        }
        String token = JWT.create()
                .withClaim("username", user.getUsername())
                .withArrayClaim("authority",authorityArray)
                .withExpiresAt(new Date(System.currentTimeMillis()+2*60*60*1000))
                .sign(Algorithm.HMAC256("salt"));
        return token;
    }

    public static TokenUser parseUserToken(String token) throws JWTVerificationException {
        JWTVerifier build = JWT.require(Algorithm.HMAC256("salt")).build();
        Map<String, Claim> claims = build.verify(token).getClaims();
        String username = claims.get("username").asString();
        List<String> authority = claims.get("authority").asList(String.class);
        return new TokenUser(username,authority);
    }
}
